package com.lge.clock.timer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.lge.clock.R;
import com.lge.clock.TimerFragment;
import com.lge.clock.util.CommonUtil;
import com.lge.clock.util.CommonUtil.CallStateHolder;
import com.lge.clock.util.Log;

/**
 * @author LGE Cappuccino
 */
public class TimerDialog extends Activity
{
	private static final int AUTO_TIMER_OUT = 1001; 
	// private static final String SCREEN_OFF = "screen_off";
	private static final String TAG = "TimerDialog";
	private static final int KEYCODE_3DCAMERA = 92; 
	private AlertDialog.Builder ad = null;
	private TelephonyManager mTelephonyManager;
	
	private CallStateHolder mInitialCallState;
	private Intent timerKilled;
//	private AudioManager mAudioManager = null;
//	private boolean mPlayingMusic = false;
	
	private static final int ONE_MILLI_SEC = 1;
    private static final int ONE_SEC = 1000 * ONE_MILLI_SEC;
    private static final int AUTO_TIMER_OUT_SEC = 180 * ONE_SEC;
	
	private final Handler mSoundHandler = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
	    	switch (msg.what) 
	    	{
	    		case AUTO_TIMER_OUT:
	    			finish();
	    			break;
	    		
	    		default :
	    			break;
	    	}
		}
	};
	
	/**
     * during it is incomming, when alarm is happend, go to snooze
     */
    private final PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String ignored) 
        {
           	if (state != TelephonyManager.CALL_STATE_IDLE && mInitialCallState.equals(CommonUtil.getNowCallState(getApplicationContext(), mTelephonyManager)) == false) 
           	{
           		Intent timerKilled = new Intent(Timers.TIMER_KILLED);
    			sendBroadcast(timerKilled);
    			Toast.makeText(getApplicationContext(), R.string.timer_done, Toast.LENGTH_SHORT).show();
           		finish();   
            }
        }     
    };
	
    /**
     * Method onCreate.
     * @param savedInstanceState Bundle
     */
    @Override
	protected void onCreate(Bundle savedInstanceState) 	{
		super.onCreate(savedInstanceState);
	    Log.d(TAG, "[onCreate]");
	    TimerWakeLock.acquireScreenWakeLock(this);//[hyunjung78.park][1427] 2011.10.13
		requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
		
//		mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
//      mPlayingMusic = mAudioManager.isMusicActive();
		
		final Window win = getWindow();
		win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
	
		Intent closeDialogs = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
		sendBroadcast(closeDialogs);
		
		mTelephonyManager =	(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
		mInitialCallState = CommonUtil.getNowCallState(getApplicationContext(), mTelephonyManager);
		
		timerKilled = new Intent(Timers.TIMER_KILLED);
		
//		Log.d(TAG,"TimerDialog onCreate sendBroadcast [Play Pause]");
//        Intent music = new Intent("com.android.music.musicservicecommand");
//        music.putExtra("command", "toggleplay");
//        music.putExtra("status", "start");
//        sendBroadcast(music);
        
    	// [start][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status"  
//        Log.d(TAG, "TimerDialog onCreate sendBroadCast [FmRadio pause]");
//        Intent fmRadio = new Intent("com.ti.server.fmresumecmd");
//        fmRadio.putExtra("status", "start");
//        sendBroadcast(fmRadio);
        // [end][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status"  
        
        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
        
		try {
			Intent playTimer = new Intent(this, TimerAlarm.class);
			playTimer.putExtra("Vibration", TimerFragment.loadVibPreferences());
			playTimer.putExtra("Ringtone", TimerFragment.loadTonePreferences());
			startService(playTimer);
		}
		catch(NullPointerException e) {
			e.printStackTrace();
		}
		/*[START] 2012.04.04 suein1209.kim*/
//		if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
		/*[END] 2012.04.04 suein1209.kim*/
		if (CommonUtil.isCallStateIdle(mTelephonyManager, getApplicationContext()) == false) {
			sendBroadcast(timerKilled);
			Toast.makeText(this, R.string.timer_done, Toast.LENGTH_SHORT).show();
			finish();
		}
		else {
			this.setContentView(R.layout.timerdialog);
			mSoundHandler.sendMessageDelayed(mSoundHandler.obtainMessage(AUTO_TIMER_OUT), AUTO_TIMER_OUT_SEC);   // 1000 * 180 * 1
		
			ad = new AlertDialog.Builder(this);
		
			ad.setIcon(android.R.drawable.ic_dialog_info)
			.setTitle(R.string.timer_done)
			//.setPositiveButton(R.string.dismiss, new DialogInterface.OnClickListener()//P930_TD#15368_20110719 Dismiss -> Stop 
			.setPositiveButton(R.string.sp_stop_name_NORMAL, new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog,	int which) {
					finish();
				}
			})
			.setOnKeyListener(new OnKeyListener() {
				public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
					switch(keyCode)
					{
						case KeyEvent.KEYCODE_BACK :
							return true;		
						case KeyEvent.KEYCODE_VOLUME_UP :
							finish();
							return true;
						case KeyEvent.KEYCODE_VOLUME_DOWN :
							finish();
							return true;
						case KEYCODE_3DCAMERA :
							finish();
							return true;
						case KeyEvent.KEYCODE_MENU :
							return true;
						case KeyEvent.KEYCODE_SEARCH :
							return true;
						default :
							return false;
					}
				}
			}).show();
		}					
	}

	/**
	 * Method onResume.
	 */
	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "[onResume]");		
	}

	/**
	 * Method finish.
	 */
	@Override
	public void finish() {
		super.finish();
		Log.d(TAG, "[Finish]");

		if(timerKilled != null)
		{
			stopService(new Intent(this, TimerAlarm.class));
			mTelephonyManager.listen(mPhoneStateListener, 0);
			
//			Log.d(TAG,"TimerDialog finish sendBroadCast [Music Restart]");
//			Intent music = new Intent("com.android.music.musicservicecommand");
//			music.putExtra("command", "toggleplay");
//			music.putExtra("status", "end");
//			sendBroadcast(music);
			
			// [start][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status"  
//	        Log.d(TAG, "TimerDialog finish sendBroadCast [FmRadio Restart]");
//	        Intent fmRadio = new Intent("com.ti.server.fmresumecmd");
//	        fmRadio.putExtra("status", "end");
//	        sendBroadcast(fmRadio);
	        // [end][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status" 
			
			TimerFragment.releaseLocks();
			sendBroadcast(timerKilled);
			timerKilled = null;
		}
	}

	/**
	 * Method onPause.
	 */
	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "[onPause]");
	}

	/**
	 * Method onStop.
	 */
	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG, "[onStop]");
		
		if(timerKilled != null) {
			stopService(new Intent(this, TimerAlarm.class));
			mTelephonyManager.listen(mPhoneStateListener, 0);
			
//			Log.d(TAG,"TimerDialog onStop sendBroadCast [Music Restart]");
//			Intent music = new Intent("com.android.music.musicservicecommand");
//			music.putExtra("command", "toggleplay");
//			music.putExtra("status", "end");
//			sendBroadcast(music);
			
	        // [start][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status"  
//	        Log.d(TAG, "TimerDialog onStop sendBroadCast [FmRadio Restart]");
//	        Intent fmRadio = new Intent("com.ti.server.fmresumecmd");
//	        fmRadio.putExtra("status", "end");
//	        sendBroadcast(fmRadio);
	        // [end][yeonju7.kim][P940] 2011.09.21 ADD Fm Radio intent "status"   

			TimerFragment.releaseLocks();
			sendBroadcast(timerKilled);
			timerKilled = null;
		}
		
		finish();
	}
	
	/**
	 * Method onDestroy.
	 */
	@Override
	protected void onDestroy() 
	{
		super.onDestroy();
		Log.d(TAG, "timerdialog[onDestroy]");
	}
	
	/**
	 * Method dispatchKeyEvent.
	 * @param event KeyEvent
	 * @return boolean
	 * @see android.view.Window$Callback#dispatchKeyEvent(KeyEvent)
	 */
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) 
	{
		Log.d(TAG, "dispatchKeyEvent : " + Integer.toString(event.getKeyCode()));
		return super.dispatchKeyEvent(event);
	}
}

